#coding=utf-8
from selenium import webdriver
import time
import re
from bs4 import BeautifulSoup
import sys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
import requests
import re 
#通过百度搜索  搜索到的词条数
def baidu_answer(pre_answer):

    header = {
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'max-age=0',
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
        }
    urls='https://www.baidu.com/s?ie=utf-8&wd='+pre_answer
    req = requests.get(url =urls,timeout=5,headers=header)
    print(urls)
    html = req.text
    #print(html)
    div_bf=BeautifulSoup(html,"html.parser")
    result=div_bf.find_all('span',class_='nums_text')
    #result=div_bf.find_all('span')
    print(result[0].text)
    zifu=result[0].text.replace('百度为您找到相关结果约','')
    zifu=zifu.replace('个','')
    zifu=zifu.replace(',','')
    print(zifu)
    return zifu
#读取账户信息
def read_login_txt():
    try:       
        f1 = open("./login.txt","r")
        lines = f1.readlines()
        f1.close()
        account=lines[0]
        password=lines[1]
        print('发现之前的账户信息')
        print('账号:'+lines[0])
        print('密码:'+lines[1])
        
        # for l in lines:
        #     print(l)
    except:
        print('未找到登陆文件，请重新输入：\n')

        account=input('请输入账号(enter结束):')
        password=input('请输入密码(enter结束):')
        f1 = open("login.txt","w")
        f1.writelines(account+'\n')
        f1.writelines(password)
        f1.close()
    return [account,password]
#登录学习通
def logindriver(m_driver,acc,pword):
    
    m_driver.get('http://i.chaoxing.com/base')   #打开网页
    m_driver.find_element_by_xpath("//*/ul/li[text()='手机号/超星号登录']").click()
    m_driver.find_element_by_xpath("//input[@placeholder='请输入手机号/超星号']").send_keys(acc)
    m_driver.find_element_by_xpath("//input[@placeholder='请输入密码']").send_keys(pword)
    time.sleep(1)
    m_driver.find_element_by_xpath("//input[@value='登录']").click()
    time.sleep(1)                                   #
    return m_driver
#选择课程
def choice_class(m_driver,source):
    div_bf=BeautifulSoup(source,"html.parser")
    result=div_bf.find_all('li',style="position:relative")
    #print(result)
    # f1.close()
    print('你共有'+str(len(result))+'门课')
    j=1
    class_group=[]
    for i in result:
        div_bf=BeautifulSoup(str(i),"html.parser")
        result=div_bf.find_all('a')
        print('>>>>>>>>>>>>')
        print(str(j)+':'+result[3].text)
        class_group.append(result[3].text)
        j=j+1
    #class_num=input('请输入你想刷的课程序号')
    class_num=3
    print('您选择了  '+class_group[int(class_num)-1])

    m_driver.find_element_by_link_text(class_group[int(class_num)-1]).click()
    return m_driver
#寻找最可能的答案  但是错误率挺高
def do_question():
    possible=[0,0,0,0]
    chioce_word=['A','B','C','D']
    # f1=open('source.txt','r')
    # html=f1.read()
    # f1.close()
    # div_bf=BeautifulSoup(html,"html.parser")
    div_bf=BeautifulSoup(m_driver.page_source,"html.parser")
    result=div_bf.find_all('div',class_="ans-videoquiz-title")
    print(result[0].text)
    ques=result[0].text.replace('[单选题] ','')
    ques.replace('[判断题]','')
    ques.replace(' ','')
    print(ques)


    result=div_bf.find_all('li',class_="ans-videoquiz-opt")
    max_possible=[0,0]

    for i in range(len(result)):
        ans_last=result[i].text.replace(chioce_word[i],'')
        ans_last.replace(' ','')
        print((ques+ans_last).replace(' ','')) 
        # possible[i]=int(baidu_answer((ques+'\"'+ans_last+'\"').replace(' ','')))
        possible[i]=int(baidu_answer((ques+ans_last).replace(' ','')))
        print(possible)
        if i>0:
            if(possible[i]>max_possible[1]):
                max_possible[0]=i
                max_possible[1]=possible[i]
        else:
            max_possible[1]=possible[i]
    print('选'+chioce_word[max_possible[0]])
    return max_possible[0]
    


   
    # print('发现题目')
    # choice=m_driver.find_elements_by_xpath("//input[@name='ans-videoquiz-opt']")
    # print('共有'+str(len(choice))+'choice')
    # submit=m_driver.find_element_by_xpath("//div[@class='ans-videoquiz-submit']")
#播放视频
def play_video(m_driver):
    m_driver.switch_to.default_content() 
    frame = m_driver.find_elements_by_tag_name('iframe')[0]  
    m_driver.switch_to.frame(frame) 
    m_driver=choice_class(m_driver,m_driver.page_source)    
    time.sleep(1)
    m_driver.switch_to.window(m_driver.window_handles[1])
    time.sleep(1)
    m_driver.find_elements_by_class_name("articlename")[0].click()
    time.sleep(1)
    #driver1=m_driver
    need_to_do=m_driver.find_elements_by_class_name("ncells")

    for i in range(len(need_to_do)):
        m_driver.switch_to.default_content()
        #driver1.switch_to.default_content()
        need_to_do=m_driver.find_elements_by_class_name("ncells")
        
        # try:
        div_bf=BeautifulSoup(m_driver.page_source,"html.parser")
        result=div_bf.find_all('div',class_="ncells")   
        
        div_bf=BeautifulSoup(str(result[i]),"html.parser")
        #print(div_bf.span)
        result=div_bf.find_all('input')
        #print(result)
        if len(result)==0:
            print('第'+str(i)+'小结已经完成，不需要刷，即将载入下一节')
        elif i==38:
            #有些章节似乎有bug
            print('跳过')
        else :
            print('第'+str(i)+'小结未完成')
            print('开始刷课')
            time.sleep(4)
            need_to_do[i].click()
            #print(i)
            time.sleep(4)
            iframe = m_driver.find_element_by_css_selector('iframe')
            m_driver.switch_to.frame(iframe)
            iframe = m_driver.find_element_by_css_selector('iframe')
            m_driver.switch_to.frame(iframe)
            mouse=m_driver.find_element_by_xpath("//div[@aria-label='视频播放器']")
            ActionChains(m_driver).move_to_element(mouse).perform()
            mouse.click()
            
            time.sleep(1)
            full_time='0:00'
            #防止因为网速太慢，页面长时间加载不出来，导致判定刷完
            while full_time=='0:00':
                div_bf=BeautifulSoup(m_driver.page_source,"html.parser")
                result=div_bf.find_all('span',class_="vjs-duration-display")   
                full_time=result[0].text
                time.sleep(1)
            now_time=''
            last_time=''
            while full_time!=now_time:
                div_bf=BeautifulSoup(m_driver.page_source,"html.parser")
                result=div_bf.find_all('span',class_="vjs-current-time-display")   
                now_time=result[0].text
                if last_time==now_time:
                    print('因为某种原因暂停')
                    #ans=input('因为某种原因暂停\n1若是题选1，\n否则enter就好')
                    #if ans=='1':
                    div_bf=BeautifulSoup(m_driver.page_source,"html.parser")
                    result=div_bf.find_all('div',class_="ans-videoquiz-submit") 
                    if len(result)!=0:
                        try:
                            print('发现题目')
                            choice=m_driver.find_elements_by_xpath("//input[@name='ans-videoquiz-opt']")
                            print('共有'+str(len(choice))+'choice')
                            submit=m_driver.find_element_by_xpath("//div[@class='ans-videoquiz-submit']")
                            choice[do_question()].click()
                            time.sleep(2)
                            submit.click()
                            time.sleep(2)
                            if EC.alert_is_present(m_driver):
                                m_driver.switch_to.alert.accept()
                                try:
                                    for j in choice:
                                        j.click()
                                        time.sleep(1)
                                        submit.click()
                                        time.sleep(2)
                                        result = EC.alert_is_present()(driver)
                                        if result:
                                            print(result.text)
                                            result.accept()
                                        else:
                                            print('alert 未弹出！')
                                        
                                except:
                                    print('对了？') 

                        except:
                            print('error-hao')
                            try:
                                for j in choice:
                                    j.click()
                                    time.sleep(1)
                                    submit.click()
                                    time.sleep(2)
                                    print('这个好像不对')
                                    result = EC.alert_is_present()(driver)
                                    if result:
                                        print(result.text)
                                        result.accept()
                                    else:
                                        print("alert 未弹出！")
                            except:
                                print('似乎答对了') 
                    else:
                        print('因为鼠标离开暂停，重新点击')
                        try:
                            m_driver.find_element_by_xpath("//button[@title='播放']").click()
                        except:
                            print('重新点击失败')
                
                        
                    # try:
                last_time=now_time
                sys.stdout.write(now_time+'/'+full_time+'\r')
                sys.stdout.flush()
                #ActionChains(m_driver).move_to_element(mouse).perform()
                #print(now_time+'/'+full_time)
                time.sleep(2)
            print(now_time+'/'+full_time+'\r')
            print('第'+str(i)+'小结完成')  


if __name__ == "__main__":
    information=read_login_txt()#读取账户信息
    opt = webdriver.ChromeOptions()                 #创建浏览器
    #opt.set_headless()                            #无窗口模式
    m_driver = webdriver.Chrome(options=opt)          #创建浏览器对象
    m_driver=logindriver(m_driver,information[0],information[1])#登录
    play_video(m_driver)#播放视频



    #baidu_answer('薛宝钗的丫头是平儿')
    #do_question()



#对比

# rsv_bp: 1
# tn: baidu
# lm: 1
# rsv_pq: e5de5a140011434b
# rsv_t: 4cbfqTIt9KbZL8iQfgyXOPhs5Q7OlA3T24xwbzOz9t7r/4ouiSO2H52EGgQ

# rsv_spt: 1
# rsv_iqid: 0xdc1ed7090000241b
# issp: 1
# rsv_bp: 1
# rsv_idx: 2
# tn: baiduhome_pg
# inputT: 1295
# rsv_t: ecf4FkCJK1N7O9kxtM0nxYBOVAGxPVYnZUI7b+p9HqWaGKfM0ChQV330aarvwduDfPCW
# rsv_n: 2
# rsv_pq: dcd0373d0011cfb5


# ie: utf-8
# f: 8
# rsv_bp: 1
# rsv_idx: 2
# tn: baiduhome_pg
# wd: 爬虫百度搜索
# rsv_spt: 1
# oq: %E7%88%AC%E8%99%AB%E7%99%BE%E5%BA%A6%E6%90%9C%E7%B4%A2
# rsv_pq: dae5e63f000ce1b1
# rsv_t: 0cf0TAIdbaXw5MYl8qXv6YV7I1KFRv67nER12d9wiG07sNQjvuHGnhYvI3RZhn4VLgMY
# rqlang: cn
# rsv_enter: 1
# rsv_dl: tb
# inputT: 7



